package com.worldstear.controller;

import com.worldstear.core.R;
import com.worldstear.core.datasource.DataSourcePro;
import com.worldstear.core.datasource.DynamicDataSource;
import com.worldstear.model.mysql.MysqlVersionVariable;
import com.worldstear.service.BaseDBService;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("mysql")
public class DataBaseController {
    final StringRedisTemplate stringRedisTemplate;
    final BaseDBService baseDBService;

    public DataBaseController(BaseDBService baseDBService, StringRedisTemplate stringRedisTemplate) {
        this.baseDBService = baseDBService;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @GetMapping("database")
    public R<List<String>> listDataBase() {
        return R.success(baseDBService.listDataBase());
    }
    @GetMapping("variables/version")
    public R<MysqlVersionVariable> showVersionVariables() {
        return R.success(baseDBService.showVersionVariables());
    }
    @GetMapping("objects")
    public R<Map<String, List<Map<String, String>>>> getAllDatabaseObjects(@RequestParam Map<String, String> queryParam) {
        return R.success(baseDBService.getAllDatabaseObjects(queryParam.get("Db")));
    }

    @GetMapping("table")
    public R<Map<String, List<Map<String, String>>>> getTableData(@RequestParam Map<String, String> queryParam) throws Exception {
        Optional.ofNullable(queryParam.get("tableSchema")).orElseThrow(() -> new Exception("参数异常"));
        Optional.ofNullable(queryParam.get("tableName")).orElseThrow(() -> new Exception("参数异常"));
        return R.success(baseDBService.getTableData(queryParam));
    }
    @PostMapping("connect")
    public R connect2DbServer(@RequestBody DataSourcePro dataSourcePro) throws Exception {
        stringRedisTemplate.delete("");
        DynamicDataSource.clear();
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(dataSourcePro.getUrl());
        hikariConfig.setUsername(dataSourcePro.getUsername());
        hikariConfig.setPassword(dataSourcePro.getPassword());
        DynamicDataSource.dataSourcesMap.put("dbkey", new HikariDataSource(hikariConfig));
        DynamicDataSource.setDataSource("dbkey");
        return R.success(this.listDataBase());
    }
}
